<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" @change="deptChange" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" placeholder="请选择" clearable >
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="特殊车辆名称">
          <el-input v-model="listQuery.name" clearable class="filter-item" placeholder="请输入特殊车辆名称"/>
        </el-form-item>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:specialCar:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list"
    element-loading-text="正在查询中。。。"
    border fit highlight-current-row >
      <el-table-column align="center" type="index" />
      <el-table-column align="center" label="所属机构" prop="departmentName"/>
      <el-table-column align="center" label="特殊车辆名称" prop="name"/>
      <el-table-column align="center" label="停车场名称" prop="parkName"/>
      <el-table-column align="center" label="创建时间" prop="createTime" />
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:specialCarInfo:list']"
            type="primary"
            size="small"
            @click="handleAddNo(scope.row)">添加车牌</el-button>
          <el-button
            v-hasPermi="['admin:specialCar:update']"
            type="primary"
            size="small"
            @click="startEditPassway(scope.row)">编辑</el-button>
          <el-button type="danger"
          v-hasPermi="['admin:specialCar:delete']"
          size="small"
          @click="deletePassway(scope.row.deviceTypeDesc, scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogFormVisible" width="28%">
      <el-form ref="dialogForm" :inline="true" :rules="formRules" :model="dialogForm" label-width="140px">
        <div v-if="dialogTitle == '新增车牌' || dialogTitle == '修改车牌'">
          <el-form-item label="车牌号码" prop="plateNumber">
            <el-input v-model="dialogForm.plateNumber"/>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label=" 机构  " prop="departmentId">
            <el-select :disabled="dialogType != 1" v-model="dialogForm.departmentId" placeholder="请选择" @change="DepartmentChange">
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label=" 停车场  " prop="parkId">
            <el-select :disabled="dialogType != 1" v-model="dialogForm.parkId"  placeholder="请选择">
              <el-option
                v-for="item in parkList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label=" 收费规则  " prop="feeRuleId">
            <el-select v-model="dialogForm.feeRuleId"  placeholder="请选择">
              <el-option
                v-for="item in feeRuleList"
                :key="item.id"
                :label="item.feeRuleName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="特殊车辆名称" prop="name">
            <el-input v-model="dialogForm.name"/>
          </el-form-item>
        </div>

      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 添加车牌弹框 -->
    <el-dialog :close-on-click-modal="false"
      :title="mxTitle"
      :visible.sync="mxOpen"
      width="1000px"
      append-to-body
    >
      <!-- 查询和其他操作 -->
      <div class="filter-container">
        <el-form :inline="true">
          <el-form-item label="车牌号">
            <el-input v-model="mxQueryParams.plateNumber" clearable class="filter-item" placeholder="请输入车牌号"/>
          </el-form-item>

          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="mxFilter">查找</el-button>

          <el-button class="filter-item"
           v-hasPermi="['admin:specialCarInfo:create']"
          @click="carOpen" icon="el-icon-plus" type="primary">添加</el-button>
        </el-form>
      </div>
      <div class="diy-mt-5">
        <el-table
          v-loading="mxListLoading"
          element-loading-text="正在查询中。。。"
          @selection-change="carSelectionChange"
          :data="mxList"
          border fit highlight-current-row
        >
        <!--  <el-table-column type="selection" width="50" align="center" />
          </el-table-column> -->
          <el-table-column
            label="序号"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column prop="plateNumber" align="center" label="车牌号码"></el-table-column>
          <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['admin:specialCarInfo:update']"
                type="primary"
                size="small"
                @click="editCar(scope.row)">编辑</el-button>
              <el-button type="danger"
              v-hasPermi="['admin:specialCarInfo:delete']"
              size="small"
              @click="delCar(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

        <pagination
          v-show="mxTotal > 0"
          :total="mxTotal"
          :page.sync="mxQueryParams.page"
          :limit.sync="mxQueryParams.pageSize"
          @pagination="getMxList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitTo">确 定</el-button> -->
        <el-button @click="mxOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, deleteSpecialCar, createSpecialCar, updateSpecialCar, specialCarDetail,
 listDepartmentRule, specialCarInfoList, deleteSpecialCarInfo, createSpecialCarInfo,
 updateSpecialCarInfo, specialCarInfoDetail,
 } from '@/api/business/specialCar'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import QRCode from 'qrcodejs2'

export default {
  name: 'specialCar',
  components: { Pagination },
  data() {
    return {
      allParkList: [],//停车昌数据
      list: null,//表格数据
      total: 0,//表格总数
      listLoading: true,//表格加载
      listQuery: {//表格搜索参数
        page: 1,
        pageSize: 10
      },
      dialogFormVisible: false,//弹窗开启关闭
      dialogForm: {},//表单数据
      dialogType: 1,//表单类型
      dialogTitle:'',//表单标题
      name: '',
      formRules: {
        departmentId: [{ required: true, message: '请选择机构', validator: this.checkSelected, trigger: 'change' }],
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }],
        name: [{ required: true, message: '请输入特殊车辆', trigger: 'blur' }],
        feeRuleId: [{ required: true, message: '请选择收费规则', validator: this.checkSelected, trigger: 'change' }],
        plateNumber: [{ required: true, message: '请输入车牌号码', trigger: 'blur' }],
      },
      parkList: [],//停车场数据
      departmentList: [],//机构数据
      feeRuleList:[],//规则数据
      mxOpen:false,//明细列表弹窗
      mxTitle:'',//明细列表弹窗标题
      mxQueryParams:{//明细列表请求参数
        page: 1,
        pageSize: 10
      },
      mxList: [],//明细列表表格数据
      mxTotal: 0,//明细列表表格总数
      mxListLoading: true,//明细列表表格加载
      mxIds:[],//选中的明细数据
      // 非单个禁用
      single: true,
      carMultiple:true,//明细列表删除按钮状态
    }
  },
  created() {
    this.getDepartmentList()
    this.getList()
  },
  methods: {
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId})
      return res.data || []
    },
    async deptChange(e){//机构下拉选择
      let listQuery = {...this.listQuery}
      listQuery.parkId = ''
      this.listQuery = {...listQuery}
      if(!e) return this.allParkList = []
      this.allParkList = await this.getListAuthPark(e)
    },
    mxFilter(){//明细列表查询
      this.mxQueryParams.page = 1
      this.getMxList()
    },
    carOpen(){//明细列表新增
      this.dialogFormVisible = true
      this.dialogType = 1
      this.dialogTitle = '新增车牌'
      this.resetForm()
    },
    editCar(row){//明细列表修改
      specialCarInfoDetail(row.id).then(async response => {
        this.dialogFormVisible = true
        this.resetForm()
        this.dialogType = 2
        this.dialogTitle = '修改车牌'
        this.dialogForm = response.data || {}
      })
    },
    delCar(id){//明细列表删除
      this.$confirm(`您确定删除该车牌`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSpecialCarInfo(id).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getMxList()
        })
      })
    },
    carSelectionChange(selection){//明细列表选择
      this.carIds = selection.map((item) => item.pkCarId);
      this.single = selection.length !== 1;
      this.carMultiple = !selection.length;
    },
    async getMxList(){
      this.mxListLoading = true
      let res = await specialCarInfoList(this.mxQueryParams)
      let obj = res.data || {}
      this.mxList = obj.list || []
      this.mxListLoading = false
      this.mxTotal = obj.total || 0
    },
    //添加车牌
    handleAddNo(row) {
      this.listObj = {...row}
      this.mxOpen = true;
      this.mxQueryParams.page = 1
      this.mxQueryParams.specialCarId = row.id
      this.getMxList()
      this.mxTitle = "添加车牌";
    },
    async listDepartmentRule(id){//机构下的收费规则列表
      let res = await listDepartmentRule({
        departmentId:id,
        types:[1,2,3]
      })
      this.feeRuleList = res.data || []
    },
    DepartmentChange(event){//机构下拉改变事件
      let dialogForm = {...this.dialogForm}
      dialogForm.parkId = ''
      dialogForm.feeRuleId = ''
      this.dialogForm = {...dialogForm}
      this.selectDepartmentId(event)
      this.listDepartmentRule(event)
    },
    async selectDepartmentId(event) {//根据机构获取停车昌数据
      this.parkList = []
      this.parkList = await this.getListAuthPark(event)
    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    deletePassway(name, parkId) {//删除
      this.$confirm(`您确定删除该特殊车辆`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSpecialCar(parkId).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {//新增
      this.dialogFormVisible = true
      this.dialogType = 1
      this.parkList = []
      this.feeRuleList = []
      this.dialogTitle = '添加特殊车辆'
      this.resetForm()
      this.getDepartmentList()
    },
    confirmEdit(formName) {//提交
      console.log(this.dialogForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle == '新增车牌' || this.dialogTitle == '修改车牌'){
            this.dialogForm.specialCarId = this.mxQueryParams.specialCarId
            if(this.dialogForm.id){
              updateSpecialCarInfo(this.dialogForm).then(response => {
                this.$message({message: '添加成功!',type: 'success'})
                this.getMxList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            }else{
              createSpecialCarInfo(this.dialogForm).then(response => {
                this.$message({message: '修改成功!',type: 'success'})
                this.getMxList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            }
          }else{
            if (this.dialogType === 1) {
              createSpecialCar(this.dialogForm).then(response => {
                this.$message({message: '添加成功!',type: 'success'})
                this.getList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            } else {
              updateSpecialCar(this.dialogForm).then(response => {
                this.$message({message: '修改成功!',type: 'success'})
                this.getList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            }
          }

        }
      })
    },
    startEditPassway(row) {//修改
      specialCarDetail(row.id).then(async response => {
        this.dialogFormVisible = true
        this.resetForm()
        this.dialogType = 2
        this.dialogTitle = '修改特殊车辆'
        this.dialogForm = response.data || {}
        this.parkList = await this.getListAuthPark(this.dialogForm.departmentId)
        this.getDepartmentList()
        this.selectDepartmentId(this.dialogForm.departmentId)
        this.listDepartmentRule(this.dialogForm.departmentId)
      })


    },
    resetForm(formName) {
      this.$nextTick(()=>{
        this.$refs['dialogForm'].clearValidate();
      })
      this.dialogForm = {}
    },
  }
}
</script>
<style scoped>
#qrcode{
  width: 250px;
  margin: 0 auto;
}
</style>
